package com.kerrykidz.system.util.sync;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component("syncDataConsumer")
public class SyncDataConsumer implements SyncConsumer {

	private final Logger log = Logger.getLogger(SyncDataConsumer.class);

	@Override
	public void doConsumer(Serializable message) {
		insertLog((MessageTask) message);
		parseAndInsert();
	}

	protected void insertLog(MessageTask message) {
		SerializableHelper.serialize(message);
		SqlHelper.insertSysDataSyncLog(message.getTaskId());
	}

	protected List<String> getNotOperateTaskId() {
		List<String> taskIds = SqlHelper.getNotOperateTask();
		return taskIds;
	}

	protected void parseAndInsert() {

		List<String> serializableIds = this.getNotOperateTaskId();

		for (String taskId : serializableIds) {

			final MessageTask task = SerializableHelper.deserialize(taskId);

			if (task != null)
				SqlHelper.executeUpdate(new SyncTransaction() {

					@Override
					public void doTransaction(JdbcTemplate jdbcTemplate) {
						List<TableSyncMessage> tables = task.getMessages();
						if (tables != null) {
							try {
								for (TableSyncMessage table : tables) {
									doInsert(table.getMessages());
								}
								commit(task.getTaskId());
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				});
		}
	}

	private void doInsert(List<SyncMessage> messages) throws Exception {
		for (SyncMessage message : messages) {
			SqlAndParam sqlAndParam = null;
			try {
				int operatype = this.getOperateType(message);
				switch (operatype) {
				case 1:
					sqlAndParam = message.getInsertSql();
					break;

				default:
					sqlAndParam = message.getUpdateSql();
					break;
				}

				Vector<Object> v = new Vector<Object>();
				for (Object o : sqlAndParam.getParams())
					v.add(o);

				this.log.info("------------->>>>>>>>>>" + sqlAndParam.getSql() + "--------------" + v);

				SqlHelper.nonTransactionExcute(sqlAndParam.getSql(), sqlAndParam.getParams());

				if (message.getRelations() != null) {
					for (RelationMessage relation : message.getRelations()) {
						SqlAndParam del = relation.getDeleteSql();
						SqlAndParam ins = relation.getBatchInsertSql();
						if (del != null)
							SqlHelper.nonTransactionExcute(del);
						if (ins != null)
							SqlHelper.nonTransactionExcute(ins);
					}
				}
			} catch (Exception e) {
				throw new Exception(sqlAndParam.getSql());
			}
		}
	}

	/**
	 * 
	 * @Desc
	 * @author QUINN
	 * @date 2014年9月25日上午10:15:42
	 * @param message
	 * @return 1为增，2为改
	 */
	private int getOperateType(SyncMessage message) {
		StringBuffer sql = new StringBuffer("SELECT * FROM ");
		sql.append(message.getTableName()).append(" WHERE ").append(message.getPrimaryKey()).append("=?");
		List<Map<String, Object>> o = SqlHelper.query(sql.toString(), message.getPrimaryValue());
		if (o.size() == 0)
			return 1;
		else
			return 2;
	}

	protected void commit(String serializeId) {
		SqlHelper.successConsumer(serializeId);
		SerializableHelper.removeSeriaFile(serializeId);
	}

}
